﻿using Newtonsoft.Json.Linq;

namespace XYS.Core.Util;

/// <summary>
/// 扩展
/// </summary>
public static partial class Extention
{
    /// <summary>
    /// 获取子集
    /// </summary>
    /// <param name="token"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public static JToken GetChild(this JToken token, string path)
    {
        return token.SelectToken($"$..{path}");
    }

    /// <summary>
    /// 获取子集
    /// </summary>
    /// <param name="token"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public static List<JToken> GetChildren(this JToken token, string path)
    {
        return token.SelectToken($"$..{path}")?.Children().ToList();
    }

    /// <summary>
    /// 获取值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="token"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public static T? GetEnumValue<T>(this JToken token, string path)
        where T : struct
    {
        string valueString = token.Value<string>(path);
        if (valueString.IsNullOrWhiteSpace()) return null;

        return Enum.TryParse<T>(valueString, out var enumVale) ? enumVale : null;
    }

    /// <summary>
    /// 获取值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="token"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public static T? GetValue<T>(this JToken token, string path)
    {
        try
        {
            if (typeof(T).IsEnum)
                throw new Exception("GetValue 的泛型类型不能为枚举，如果需要获取枚举类型，请使用GetEnumValue");

            return token.Value<T>(path) ?? default;
        }
        catch { return default; }
    }

}
